package experiment3.shudu001.activity;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.TextView;
import java.util.concurrent.TimeUnit;
import experiment3.shudu001.R;
import experiment3.shudu001.models.PrefsManager;

public class StatisticsActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_statistics);

        // 加载统计数据
        int[] gamesPlayed = PrefsManager.getGamesPlayed(this);
        long[] bestTimes = PrefsManager.getBestTimes(this);
        int[] bestMistakes = PrefsManager.getBestMistakes(this);

        // 显示统计数据
        displayStats(gamesPlayed[0], bestTimes[0], bestMistakes[0],
                R.id.easyGamesPlayedTextView,
                R.id.easyBestTimeTextView,
                R.id.eastBestMistakesTextView);

        displayStats(gamesPlayed[1], bestTimes[1], bestMistakes[1],
                R.id.mediumGamesPlayedTextView,
                R.id.mediumBestTimeTextView,
                R.id.mediumBestMistakesTextView);

        displayStats(gamesPlayed[2], bestTimes[2], bestMistakes[2],
                R.id.hardGamesPlayedTextView,
                R.id.hardBestTimeTextView,
                R.id.hardBestMistakesTextView);

        findViewById(R.id.backButtonStats).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    private void displayStats(int games, long time, int mistakes,
                              int gamesTextViewId, int timeTextViewId, int mistakesTextViewId) {

        TextView gamesTextView = (TextView) findViewById(gamesTextViewId);
        TextView timeTextView = (TextView) findViewById(timeTextViewId);
        TextView mistakesTextView = (TextView) findViewById(mistakesTextViewId);

        gamesTextView.setText("游戏次数: " + games);

        if (time > 0) {
            String timeFormatted = String.format("%02d:%02d",
                    TimeUnit.MILLISECONDS.toMinutes(time),
                    TimeUnit.MILLISECONDS.toSeconds(time) -
                            TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(time)));
            timeTextView.setText("最佳时间: " + timeFormatted);
        } else {
            timeTextView.setText("最佳时间: --:--");
        }

        mistakesTextView.setText("最少错误: " + (mistakes == Integer.MAX_VALUE ? "--" : mistakes));
    }
}